package ui;

import utils.HtmlReportUtil;
import utils.CsvReportUtil;
import utils.LoggerUtil;
import utils.ConfigUtil;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;

public class SaveRestorePanel extends JPanel {
    private JComboBox<String> fileTypeComboBox;
    private JComboBox<String> exportFilterComboBox;
    private JCheckBox removeDuplicatesCheckBox;
    private PermissionTestPanel permissionTestPanel;

    public SaveRestorePanel() {
        initializeComponents();
    }

    // 添加设置PermissionTestPanel的方法
    public void setPermissionTestPanel(PermissionTestPanel panel) {
        this.permissionTestPanel = panel;
    }

    private void initializeComponents() {
        setLayout(new BorderLayout());

        // 创建保存/恢复设置面板
        JPanel saveRestoreSettingsPanel = new JPanel();
        saveRestoreSettingsPanel.setLayout(new BoxLayout(saveRestoreSettingsPanel, BoxLayout.Y_AXIS));
        saveRestoreSettingsPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 文件类型标签和下拉框
        JPanel fileTypePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        fileTypePanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        fileTypePanel.add(new JLabel("文件类型:"));
        fileTypeComboBox = new JComboBox<>(new String[]{"HTML", "CSV"});
        fileTypeComboBox.setSelectedItem("HTML"); // 默认选择HTML
        fileTypePanel.add(fileTypeComboBox);
        saveRestoreSettingsPanel.add(fileTypePanel);

        // 导出过滤标签和下拉框
        JPanel exportFilterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        exportFilterPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        exportFilterPanel.add(new JLabel("导出过滤:"));
        exportFilterComboBox = new JComboBox<>(new String[]{"全部", "被绕过", "待确认", "可防御"});
        exportFilterComboBox.setSelectedItem("全部"); // 默认选择全部
        exportFilterPanel.add(exportFilterComboBox);
        saveRestoreSettingsPanel.add(exportFilterPanel);

        // 去除重复项复选框（默认勾选）
        JPanel removeDuplicatesPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        removeDuplicatesPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        removeDuplicatesCheckBox = new JCheckBox("去除重复项", true); // 默认勾选
        removeDuplicatesPanel.add(removeDuplicatesCheckBox);
        saveRestoreSettingsPanel.add(removeDuplicatesPanel);

        // 导出按钮
        JPanel saveButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        saveButtonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        JButton saveButton = new JButton("导出报告");
        saveButton.addActionListener(e -> saveTestResults());
        saveButtonPanel.add(saveButton);
        saveRestoreSettingsPanel.add(saveButtonPanel);


        // 添加分割线
        JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
        separator.setAlignmentX(Component.LEFT_ALIGNMENT);
        saveRestoreSettingsPanel.add(separator);

        // 添加配置状态标签
        JPanel configStatusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        configStatusPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        configStatusPanel.add(new JLabel("配置状态："));
        saveRestoreSettingsPanel.add(configStatusPanel);

        // 添加保存和恢复按钮
        JPanel configButtonPanel = getConfigButtonPanel();
        saveRestoreSettingsPanel.add(configButtonPanel);

        add(saveRestoreSettingsPanel, BorderLayout.NORTH);
    }

    private JPanel getConfigButtonPanel() {
        JPanel configButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        configButtonPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
        JButton saveConfigButton = new JButton("保存");
        saveConfigButton.addActionListener(e -> ConfigUtil.saveConfiguration(this, permissionTestPanel, fileTypeComboBox, exportFilterComboBox, removeDuplicatesCheckBox));
        JButton restoreConfigButton = new JButton("恢复");
        restoreConfigButton.addActionListener(e -> ConfigUtil.restoreConfiguration(this, permissionTestPanel, fileTypeComboBox, exportFilterComboBox, removeDuplicatesCheckBox));
        configButtonPanel.add(saveConfigButton);
        configButtonPanel.add(restoreConfigButton);
        return configButtonPanel;
    }

    // 保存测试结果的方法
    private void saveTestResults() {
        LoggerUtil.logOutput("保存" + fileTypeComboBox.getSelectedItem() + "格式的测试结果，过滤条件: " + exportFilterComboBox.getSelectedItem() + "，去除重复项: " + removeDuplicatesCheckBox.isSelected());

        String fileType = (String) fileTypeComboBox.getSelectedItem();
        if ("HTML".equals(fileType)) {
            exportHtmlReport();
        } else if ("CSV".equals(fileType)) {
            exportCsvReport();
        } else {
            JOptionPane.showMessageDialog(this, "不支持的格式", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 导出HTML报告
    private void exportHtmlReport() {
        if (permissionTestPanel == null) {
            JOptionPane.showMessageDialog(this, "无法获取测试数据", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("保存HTML报告");
        fileChooser.setSelectedFile(new File("PermissionTest_Report.html"));

        int userSelection = fileChooser.showSaveDialog(this);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();
            String filePath = fileToSave.getAbsolutePath();

            // 确保文件有.html扩展名
            if (!filePath.endsWith(".html") && !filePath.endsWith(".HTML")) {
                filePath += ".html";
                fileToSave = new File(filePath);
            }

            try {
                // 使用工具类生成HTML报告
                HtmlReportUtil.generateHtmlReport(
                    fileToSave,
                    permissionTestPanel.getTableModel(),
                    permissionTestPanel.getRenderersForColumn(6), // 低权限结果列
                    permissionTestPanel.getRenderersForColumn(7),  // 未授权结果列
                    (String) exportFilterComboBox.getSelectedItem(),  // 过滤条件
                    removeDuplicatesCheckBox.isSelected()  // 去重选项
                );
                JOptionPane.showMessageDialog(this, "报告已成功导出到: " + filePath, "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "导出报告失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                LoggerUtil.logError("导出HTML报告失败: " + e.getMessage());
            }
        }
    }

    // 导出CSV报告
    private void exportCsvReport() {
        if (permissionTestPanel == null) {
            JOptionPane.showMessageDialog(this, "无法获取测试数据", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("保存CSV报告");
        fileChooser.setSelectedFile(new File("PermissionTest_Report.csv"));

        int userSelection = fileChooser.showSaveDialog(this);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();
            String filePath = fileToSave.getAbsolutePath();

            // 确保文件有.csv扩展名
            if (!filePath.endsWith(".csv") && !filePath.endsWith(".CSV")) {
                filePath += ".csv";
                fileToSave = new File(filePath);
            }

            try {
                // 使用工具类生成CSV报告
                CsvReportUtil.generateCsvReport(
                    fileToSave,
                    permissionTestPanel.getTableModel(),
                    (String) exportFilterComboBox.getSelectedItem(),  // 过滤条件
                    removeDuplicatesCheckBox.isSelected()  // 去重选项
                );
                JOptionPane.showMessageDialog(this, "报告已成功导出到: " + filePath, "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "导出报告失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                LoggerUtil.logError("导出CSV报告失败: " + e.getMessage());
            }
        }
    }
}
